package com.mrogrape.notepad.activity.action.item;

import java.awt.event.ActionEvent;

import javax.swing.Action;
import javax.swing.text.BadLocationException;

import com.mrogrape.notepad.activity.action.NotepadAction;
import com.mrogrape.notepad.data.ViewContext;
import com.mrogrape.notepad.ui.editor.TextEditor;
import com.mrogrape.util.StringUtils;

/**
 * 调整选择范围内行的行宽到最大行。
 * 
 * @author IceSpring
 *
 */
public class FixLineToMaxMenuItemAction extends NotepadAction {

	/** serialVersionUID */
	private static final long serialVersionUID = -1L;

	public FixLineToMaxMenuItemAction() {

		super.putValue(Action.NAME, "Fix Line to Max Line Width");
		super.putValue(Action.SHORT_DESCRIPTION,
				"Append blank character to the end of line to makes line width equals max line width in selection.");
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {

		TextEditor editor = ViewContext.getMainFrame().getCurrentTextEditor();
		if (editor == null || !editor.isEditable() || !editor.isEnabled()) {
			return;
		}

		// 获取选择起始点和终点
		int selectionStart = editor.getSelectionStart();
		int selectionEnd = editor.getSelectionEnd();
		
		if(selectionStart == selectionEnd){
			return;
		}
		
		try {
			// 开始自动编辑过程，保证用户在撤销操作时不是分步撤销本次所做的编辑。
			editor.beginAtomicEdit();
			
			// 获取选择的行
			int lineStart = editor.getLineOfOffset(selectionStart);
			int lineEnd = editor.getLineOfOffset(selectionEnd);
			
			// 计算最大行宽
			int maxLength = 0;
			for(int i = lineStart; i <= lineEnd; i++){
				
				String line = editor.getTextOfLine(i);
				if(line.endsWith("\n")){
					line = line.substring(0, line.length() - 1);
				}
				if(line.endsWith("\r")){
					line = line.substring(0, line.length() - 1);
				}
				maxLength = Math.max(maxLength, line.length());
			}
			
			// 替换选择的所有行
			for(int i = lineStart; i <= lineEnd; i++){
				
				String line = editor.getTextOfLine(i);
				String endOfLine = "";
				if(line.endsWith("\n")){
					line = line.substring(0, line.length() - 1);
					endOfLine = "\n";
				}
				if(line.endsWith("\r")){
					line = line.substring(0, line.length() - 1);
					endOfLine = '\r' + endOfLine;
				}
				if(maxLength > line.length()){
					
					line += StringUtils.repeatString(" ", maxLength - line.length());
				}
				
				line += endOfLine;
				editor.replaceLine(i, line);
			}
			
		} catch (BadLocationException e) {
			
			// 通常意义上不会发生错误
			e.printStackTrace();
		} finally{
			
			// 关闭自动编辑过程
			editor.endAtomicEdit();
		}
	}
	
}
